package be.destin.scheme.search;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import be.destin.abdera.AskosiProviderServlet;
import be.destin.skos.core.SkosManager;
import be.destin.skos.html.SkosHtmlManager;

/**
 * Servlet for Autocomplete using data from DSpace SQL database
 * 2 parameters from URL:
 *  1) index: name of the query in the configuration (autocomple.query.index-name=SQL query returning two fields: name and value
 *    SQL result "name" field is used as the effective value (to search, to store, etc.)
 *    SQL result "value" field is used as the  corresponding displayed value
 *    SQL result "count" field should provide the frequency of the value
 *  2) current: value searched that is provided as a unique parameter to the SQL query
 * 
 * @author Christophe Dupriez
 * @version $Revision: 1.22 $
 */

public abstract class AskosiServlet extends HttpServlet {

    /** Logger */
    private static Logger log = Logger.getLogger(AskosiServlet.class);

    static final long serialVersionUID = 1;

    SkosManager skosManager = null;
    String host = "";
    
    // Duplicated from AskosiProviderServlet
	synchronized public void initAskosiSchemes () {
		if (skosManager == null) {
			ServletContext context = this.getServletContext();
			if (context == null) return;
			host = context.getInitParameter("base");
			if (host == null) host = System.getProperty("base");
			if (host == null) host = context.getContextPath(); // Application root is missing!
			
			String skosDirectory = context.getInitParameter(SkosHtmlManager.SKOSdirectoryParam);
			if (skosDirectory == null) skosDirectory = System.getProperty(SkosHtmlManager.SKOSdirectoryParam);
			skosManager = SkosManager.getInstance(skosDirectory);
			skosManager.setApplicationProxy(context.getInitParameter(SkosManager.ApplicationProxyParam));
			skosManager.initApplication(SkosHtmlManager.askosiDisplayApplication,host);
			String toPreload = context.getInitParameter(SkosHtmlManager.SKOSpreloadParam);
			if (toPreload == null) toPreload = System.getProperty(SkosHtmlManager.SKOSpreloadParam);
			if (toPreload != null) {
				StringTokenizer st = new StringTokenizer(toPreload,";\n, ");
				while (st.hasMoreTokens()) {
					String codeScheme = st.nextToken();
					skosManager.openScheme(codeScheme);
				}
			}
		}
	}

}
